package com.esproject.esutils;

import com.alibaba.fastjson.JSON;
import com.esproject.Annonation.ESIndexField;
import com.esproject.bean.CvInfo;
import com.esproject.esFactory.ElasticClientFactory;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;

import java.util.List;
import java.util.Map;

/**
 * ES的操作工具类
 *
 * Created by yan_li on 2017/2/19.
 */
public class EsUtils {

    /**
     * 单条保存索引
     *
     * @param indexName
     * @param typeName
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String insertEntry(String indexName, String typeName, T t) {
        Map<String, Object> stringObjectMap = AnnonResolverFieldValue.buider().clazz(t.getClass()).instanceObj(t).annotation(ESIndexField.class).build().ResolverFieldValue();
        IndexRequestBuilder builder = ElasticClientFactory.getClient().prepareIndex(indexName, typeName).setSource(stringObjectMap);
        String _es_id = (String) stringObjectMap.get("_es_id");
        if (StringUtils.isNotBlank(_es_id)) {
            builder.setId(_es_id);
        }
        IndexResponse response = builder.execute().actionGet();
        return response.getId();
    }

    /**
     * 批量保存
     *
     * @param indexName
     * @param typeName
     * @param tList
     * @param <T>
     * @return
     */
    public static <T> BulkResponse bulkInsert(String indexName, String typeName, List<T> tList) {
        BulkRequestBuilder bulkRequestBuilder = ElasticClientFactory.getClient().prepareBulk();
        for (T t : tList) {
            Map<String, Object> stringObjectMap = AnnonResolverFieldValue.buider().clazz(CvInfo.class).instanceObj(t).annotation(ESIndexField.class).build().ResolverFieldValue();
            IndexRequestBuilder indexRequestBuilder = ElasticClientFactory.getClient().prepareIndex(indexName, typeName).setSource(stringObjectMap);
            String _es_id = (String) stringObjectMap.get("_es_id");
            if (StringUtils.isNotBlank(_es_id)) {
                indexRequestBuilder.setId(_es_id);
            }
            bulkRequestBuilder.add(indexRequestBuilder);
        }
        BulkResponse response = bulkRequestBuilder.execute().actionGet();
        return response;
    }
    public static <T> UpdateResponse upinsert(String indexName, String typeName, T t) {
        try {
            UpdateRequestBuilder req = ElasticClientFactory.getClient().prepareUpdate();
            Map<String, Object> stringObjectMap = AnnonResolverFieldValue.buider().clazz(CvInfo.class).instanceObj(t).annotation(ESIndexField.class).build().ResolverFieldValue();
            String _es_id = (String) stringObjectMap.get("_es_id");
            if (StringUtils.isBlank(_es_id)) {
                return null;
            }
            UpdateResponse updateResponse = req.setIndex(indexName).setType(typeName).setId(_es_id).setDoc(stringObjectMap).setUpsert(stringObjectMap).execute().actionGet();
            return updateResponse;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 更新字段数据
     *
     * @param IndexName
     * @param typeName
     * @param t
     * @param <T>
     * @return
     */
    public static <T> UpdateResponse updateValue(String IndexName, String typeName, T t) {
        try {
            UpdateRequestBuilder req = ElasticClientFactory.getClient().prepareUpdate();
            Map<String, Object> stringObjectMap = AnnonResolverFieldValue.buider().clazz(CvInfo.class).instanceObj(t).annotation(ESIndexField.class).build().ResolverFieldValue();
            String _es_id = (String) stringObjectMap.get("_es_id");
            if (StringUtils.isBlank(_es_id)) {
                return null;
            }
            UpdateResponse updateResponse = req.setIndex(IndexName).setType(typeName).setId(_es_id).setDoc(stringObjectMap).execute().actionGet();
            return updateResponse;
        } catch (Exception e) {
            String message = e.getMessage();
            if (StringUtils.isNotBlank(message) && message.contains("document missing")) {//为避免更新没有doc抛异常
                return null;
            }
            e.printStackTrace();
        }
        return null;
    }


    public static void getAnalyResult(String content){
        AnalyzeResponse ik = ElasticClientFactory.getClient().admin().indices().prepareAnalyze(content).setAnalyzer("ik").execute().actionGet();
        System.out.println(JSON.toJSONString(ik));
    }

    /**
     * 根据id获取数据
     * @param IndexName
     * @param typeName
     * @param id
     * @param clazz
     * @return
     */
    public static Object getById(String IndexName, String typeName, String id, Class clazz) {
        GetRequestBuilder getRequestBuilder = ElasticClientFactory.getClient().prepareGet(IndexName, typeName, id);
        GetResponse getFields = getRequestBuilder.execute().actionGet();
        Map<String, Object> source = getFields.getSource();
        Object obj = JSON.parseObject(JSON.toJSONString(source), clazz);
        return obj;
    }

    public static void main(String[] args) {
        getAnalyResult("销售代表");
    }
}
